package tool

import (
	"crypto/tls"
	"fmt"
	"github.com/jordan-wright/email"
	"net/smtp"
)

type EmailClient struct {
	Addr     string
	UserName string
	Password string
	Host     string
	e        *email.Email
}

type EmailConfig struct {
	Addr     string
	UserName string
	Password string
	Host     string
}

func NewEmailClient(config *EmailConfig) *EmailClient {
	e := email.NewEmail()
	return &EmailClient{
		Addr:     config.Addr,
		UserName: config.UserName,
		Password: config.Password,
		Host:     config.Host,
		e:        e,
	}
}

func (c EmailClient) SendCode(to, code string) error {
	c.e.From = fmt.Sprintf("get <%s>", c.UserName)
	c.e.To = []string{to}
	c.e.Subject = "注册验证码"
	c.e.HTML = []byte(fmt.Sprintf("<h1>你好，你的验证码为：%s</h1>", code))

	err := c.e.SendWithTLS(c.Addr, smtp.PlainAuth("", c.UserName, c.Password, c.Host),
		&tls.Config{InsecureSkipVerify: true, ServerName: c.Host},
	)
	return err
}
